﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;
using System.Drawing;
using System.Diagnostics;

namespace ChatTool
{
    public class FileOperate
    {
        public static string RootDir = Application.StartupPath + "/systemData/";
        /// <summary>
        /// 将User对象写入文件中
        /// </summary>
        public static bool WriteUserToFile(User user)
        {
            string userPath = RootDir + "/RecordFile/userInfo.dat";
            return SerializeFile(userPath, user);

        }
        /// <summary>
        /// 从文件中获取User对象
        /// </summary>
        public static User GetUserFromFile()
        {
            string userPath = RootDir + "/RecordFile/userInfo.dat";
            return DeserializeFile(userPath) as User;
        }
        /// <summary>
        /// 从文件中获取FriendsGroup[]对象
        /// </summary>
        public static FriendsGroup[] GetFriendsGroupFromFile()
        {
            string userPath = RootDir + "/RecordFile/fridendsGroup.dat";
            return DeserializeFile(userPath) as FriendsGroup[];
        }
        /// <summary>
        /// 将FriendsGroup[]对象写入文件中
        /// </summary>
        public static void WriteFriendsGroupsToFile(FriendsGroup[] fridendsGroup)
        {
            string userPath = RootDir + "/RecordFile/fridendsGroup.dat";
            if (SerializeFile(userPath, fridendsGroup) == false)
                MessageBox.Show("将FriendsGroup[]对象写入文件[" + userPath + "]失败！");
        }
        /// <summary>
        /// 序列化对象到制定文件中
        /// </summary>
        public static bool SerializeFile(string filePath, Object obj)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                using (FileStream fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None))
                {
                    formatter.Serialize(fs, obj);
                    fs.Close();
                }
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        /// 将制定文件中的字节流信息反序列化为对象
        /// </summary>
        public static Object DeserializeFile(string filePath)
        {
            try
            {
                IFormatter formatter = new BinaryFormatter();
                using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.None))
                {
                    Object obj = formatter.Deserialize(fs);
                    fs.Close();
                    return obj;
                }
            }
            catch (Exception)
            {
                return null;
            }

        }
        /// <summary>
        /// 序列化对象为字节数组
        /// </summary>
        public static byte[] Serialize(Object obj)
        {
            IFormatter formatter = new BinaryFormatter();
            using (MemoryStream ms = new MemoryStream())
            {
                formatter.Serialize(ms, obj);
                return ms.GetBuffer();
            }
        }
        /// <summary>
        /// 将字节数组还原为对象
        /// </summary>
        public static Object Deserialize(byte[] bs)
        {
            using (MemoryStream ms = new MemoryStream(bs))
            {
                IFormatter formatter = new BinaryFormatter();
                return formatter.Deserialize(ms);
            }
        }
        /// <summary>
        /// 清空fridendsGroup.txt
        /// </summary>
        public static void ClearFriendsGroupsToFile()
        {
            string userPath = RootDir + "/RecordFile/fridendsGroup.dat";
            File.WriteAllText(userPath, "");
        }
        /// <summary>
        /// 获取表情图片
        /// </summary>
        public static System.Drawing.Bitmap[] GetFaces()
        {
            try
            {
                string facesDirPath = RootDir + "/Face/";
                string[] filePaths = Directory.GetFiles(facesDirPath, "*.gif");
                Bitmap[] faces = new Bitmap[filePaths.Length];
                int i = 0;
                foreach (string path in filePaths)
                {
                    Bitmap old = new Bitmap(path);
                    faces[i++] = old;
                }
                return faces;
            }
            catch (Exception)
            {
                return null;
            }
        }
        /// <summary>
        /// 保存聊天记录
        /// </summary>
        public static void WriteChatRecordToFile(string hisIP, DateTime startTime, string chatRtf)
        {
            string fileName = hisIP + ".dat";
            string recordPath = RootDir + "/ChatRecord/" + fileName;
            if (File.Exists(recordPath) == false)
                (File.Create(recordPath)).Close();
            ChatRecord chatRecord = new ChatRecord();
            chatRecord.StartDateTime = startTime.ToString();
            chatRecord.EndDateTime = DateTime.Now.ToString();
            chatRecord.ChatContent = chatRtf;

            List<ChatRecord> chatRecordList = FileOperate.DeserializeFile(recordPath) as List<ChatRecord>;
            if (chatRecordList == null)
                chatRecordList = new List<ChatRecord>();
            chatRecordList.Add(chatRecord);
            FileOperate.SerializeFile(recordPath, chatRecordList);
        }
        /// <summary>
        /// 获取聊天记录
        /// </summary>
        public static List<ChatRecord> GetChatRecordFromFile(string ip)
        {
            string fileName = ip + ".dat";
            string recordPath = RootDir + "/ChatRecord/" + fileName;
            if (File.Exists(recordPath))
            {
                return (FileOperate.DeserializeFile(recordPath) as List<ChatRecord>);
            }
            return null;
        }
        /// <summary>
        /// 写入删除某些条聊天记录后的聊天记录
        /// </summary>
        public static void WriteChatRecordToFile(string ip, List<ChatRecord> chatRecordList)
        {
            string fileName = ip + ".dat";
            string recordPath = RootDir + "/ChatRecord/" + fileName;
            if (File.Exists(recordPath) == false)
                (File.Create(recordPath)).Close();
            FileOperate.SerializeFile(recordPath, chatRecordList);
        }
        /// <summary>
        /// 获取群组
        /// </summary>
        public static List<Group> GroupFromFile()
        {
            string userPath = RootDir + "/RecordFile/group.dat";
            return DeserializeFile(userPath) as List<Group>;
        }
        /// <summary>
        /// 将群组写入文件
        /// </summary>
        /// <param name="list"></param>
        public static bool WriteGroupToFile(List<Group> list)
        {
            string userPath = RootDir + "/RecordFile/group.dat";
            return FileOperate.SerializeFile(userPath, list);
        }
        /// <summary>
        /// 将系统配置数据写入文件
        /// </summary>
        /// <param name="pz">配置数据</param>
        public static void WritePeiZhiToFile(string[] pz)
        {
            string userPath = RootDir + "/RecordFile/peiZhi.dat";
            File.WriteAllLines(userPath, pz);
        }
        /// <summary>
        /// 获取系统配置数据
        /// </summary>
        public static string[] GetPeiZhiFromFile()
        {
            string userPath = RootDir + "/RecordFile/peiZhi.dat";
            if (File.Exists(userPath) == false)
                (File.Create(userPath)).Close();
            return File.ReadAllLines(userPath);
        }
        /// <summary>
        /// 初始化系统数据
        /// </summary>
        public static void InitSystem()
        {
            string[] filePaths = Directory.GetFiles(RootDir + "/ChatRecord/");
            foreach (string item in filePaths)
            {
                File.Delete(item);
            }
            filePaths = Directory.GetFiles(RootDir + "/RecordFile/");
            foreach (string item in filePaths)
            {
                File.Delete(item);
            }
        }
    }
}
